import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../screens/home/model/comic_category_item_model.dart';
import '../utils/http_helper.dart';

// 漫画列表状态类
class ManhuaListState {
  final List<ComicItemModel> comics;
  final bool isLoading;
  final bool isLoadingMore;
  final bool hasError;
  final String? errorMessage;
  final bool hasMore;
  final int currentPage;

  const ManhuaListState({
    this.comics = const [],
    this.isLoading = false,
    this.isLoadingMore = false,
    this.hasError = false,
    this.errorMessage,
    this.hasMore = true,
    this.currentPage = 1,
  });

  ManhuaListState copyWith({
    List<ComicItemModel>? comics,
    bool? isLoading,
    bool? isLoadingMore,
    bool? hasError,
    String? errorMessage,
    bool? hasMore,
    int? currentPage,
  }) {
    return ManhuaListState(
      comics: comics ?? this.comics,
      isLoading: isLoading ?? this.isLoading,
      isLoadingMore: isLoadingMore ?? this.isLoadingMore,
      hasError: hasError ?? this.hasError,
      errorMessage: errorMessage ?? this.errorMessage,
      hasMore: hasMore ?? this.hasMore,
      currentPage: currentPage ?? this.currentPage,
    );
  }
}

// 漫画列表 Provider
final manhuaListProvider = StateNotifierProvider.family<ManhuaListNotifier,
    ManhuaListState, ManhuaListParams>((ref, params) {
  return ManhuaListNotifier(params);
});

// 参数类
class ManhuaListParams {
  final String categoryId;
  int? sortBy;
  int? ChargeStatus;

  ManhuaListParams({
    this.ChargeStatus,
    required this.categoryId,
    this.sortBy,
  });

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is ManhuaListParams &&
        other.categoryId == categoryId &&
        other.sortBy == sortBy;
  }

  @override
  int get hashCode => categoryId.hashCode ^ sortBy.hashCode;
}

// 漫画列表状态管理器
class ManhuaListNotifier extends StateNotifier<ManhuaListState> {
  final ManhuaListParams params;
  static const int pageSize = 10;

  ManhuaListNotifier(this.params) : super(const ManhuaListState()) {
    loadData();
  }

  // 加载数据
  Future<void> loadData({bool isRefresh = false}) async {
    if (isRefresh) {
      state = state.copyWith(
        isLoading: true,
        hasError: false,
        errorMessage: null,
        currentPage: 1,
      );
    } else if (state.currentPage == 1) {
      state = state.copyWith(
        isLoading: true,
        hasError: false,
        errorMessage: null,
      );
    }

    try {
      final response = await HttpUtil().getModel<List<ComicItemModel>>(
        'Comic/GetComicList',
        params: {
          "categoryId": params.categoryId,
          "SortBy": params.sortBy,
          "PageSize": pageSize,
          "PageNo": isRefresh ? 1 : state.currentPage,
        },
        fromJson: (json) => (json as List)
            .map((item) => ComicItemModel.fromJson(item))
            .toList(),
      );

      if (response?.status == 200 && response?.result != null) {
        final newComics = response!.result!;
        final hasMore = newComics.length >= pageSize;

        if (isRefresh || state.currentPage == 1) {
          state = state.copyWith(
            comics: newComics,
            isLoading: false,
            hasError: false,
            hasMore: hasMore,
            currentPage: 1,
          );
        } else {
          state = state.copyWith(
            comics: [...state.comics, ...newComics],
            isLoadingMore: false,
            hasError: false,
            hasMore: hasMore,
          );
        }
      } else {
        state = state.copyWith(
          isLoading: false,
          isLoadingMore: false,
          hasError: true,
          errorMessage: '加载失败，请重试',
        );
      }
    } catch (error) {
      state = state.copyWith(
        isLoading: false,
        isLoadingMore: false,
        hasError: true,
        errorMessage: error.toString(),
      );
    }
  }

  // 加载更多
  Future<void> loadMore() async {
    if (state.isLoadingMore || !state.hasMore || state.isLoading) return;

    state = state.copyWith(
      isLoadingMore: true,
      currentPage: state.currentPage + 1,
    );

    await loadData();
  }

  // 刷新
  Future<void> refresh() async {
    await loadData(isRefresh: true);
  }
}
